//
//  LoginManager.m
//  KEREN
//
//  Created by MW on 2023/3/8.
//

#import "LoginManager.h"
#import "KRTabarController.h"

//考虑将账号密码存入keychain

@implementation LoginManager
+(instancetype)sharedInstance{
    static LoginManager *loginManager = nil;
    if (loginManager == nil) {
        loginManager = [[LoginManager alloc] init];
    }
    return loginManager;
}

-(void)wxLogin{
    
    SendAuthReq *req = [[SendAuthReq alloc] init];
    req.scope = @"snsapi_userinfo"; // 只能填 snsapi_userinfo
    req.state = @"keren_wx_login";
        //第三方向微信终端发送一个SendAuthReq消息结构
    [WXApi sendReq:req completion:^(BOOL success) {
    }];
}

- (void)getWXAuthResp:(SendAuthResp *)resp{
    //091eo5Ga1PaCcF0upfHa1YFy2O0eo5GF
    DDLogInfo(@"resp === %@",resp);
    NSString *url = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",WXAppID,WXAppSecret,resp.code];
    [NetworkingTool GET:url  parameters:@{} isDeviceUrl:NO success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        //oD9H65-fHG2ogOkimYwFONy6eoPU
        if(response[@"openid"]){
            [self login:2 anduserId:response[@"openid"]];
        }else{
            [[KRAlartManager shareInstance] showAlert:@"微信授权校验失败,请重试"];
        }

    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        
    }];
}

-(void)appleLogin{
    if (@available(iOS 13.0, *)) {
        
        ASAuthorizationAppleIDProvider *appleIDProvider = [[ASAuthorizationAppleIDProvider alloc] init];
        ASAuthorizationAppleIDRequest *appleIDRequest = [appleIDProvider createRequest];
        // 用户授权请求的联系信息
        appleIDRequest.requestedScopes = @[ASAuthorizationScopeFullName, ASAuthorizationScopeEmail];
        ASAuthorizationController *authorizationController = [[ASAuthorizationController alloc] initWithAuthorizationRequests:@[appleIDRequest]];
        // 设置授权控制器通知授权请求的成功与失败的代理
        authorizationController.delegate = self;
        // 设置提供 展示上下文的代理，在这个上下文中 系统可以展示授权界面给用户
        authorizationController.presentationContextProvider = self;
        // 在控制器初始化期间启动授权流
        [authorizationController performRequests];
    } else {
        DDLogInfo(@"该系统版本不可用Apple登录");
    }
}
-(void)faceIdLogin{
    [self checkUnlockSupportType];
}

+ (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size{
    // 创建一个bitmap的context
    CGFloat width = CGImageGetWidth(img.CGImage);
    CGFloat height = CGImageGetHeight(img.CGImage);
 
    CGFloat max = width >= height ? width:height;
    CGSize originSize;
    if (max <= 0) {
        return nil;
    }
    if (width >= height) {
        originSize = CGSizeMake(size.width, (size.width * height)/width);
    }else{
        originSize = CGSizeMake((size.height * width)/height, size.height);
    }
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(size);
    // 绘制改变大小的图片
    [img drawInRect:CGRectMake((size.width - originSize.width)/2, (size.height - originSize.height)/2, originSize.width, originSize.height)];
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    // 返回新的改变大小后的图片
    return scaledImage;
}

+ (UIImage *)imageFromImage:(UIImage *)image inRect:(CGRect)rect {
    CGImageRef sourceImageRef = [image CGImage];
    CGImageRef newImageRef = CGImageCreateWithImageInRect(sourceImageRef, rect);
    UIImage *newImage = [UIImage imageWithCGImage:newImageRef];
    CGImageRelease(newImageRef);
    return newImage;
}

- (CGFloat )mostColor:(UIImage *)image scale:(CGFloat)scale{
 
 
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_6_1
    int bitmapInfo = kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedLast;
#else
    int bitmapInfo = kCGImageAlphaPremultipliedLast;
#endif
    if (scale <= 0.1) {
        scale = 0.1;
    }else if(scale >= 1){
        scale = 1;
    }
 
    //第一步 先把图片缩小 加快计算速度. 但越小结果误差可能越大
        CGSize thumbSize=CGSizeMake([image size].width * scale, [image size].height * scale);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(NULL,
                                                 thumbSize.width,
                                                 thumbSize.height,
                                                 8,//bits per component
                                                 thumbSize.width*4,
                                                 colorSpace,
                                                 bitmapInfo);
 
    CGRect drawRect = CGRectMake(0, 0, thumbSize.width, thumbSize.height);
    CGContextDrawImage(context, drawRect, image.CGImage);
    CGColorSpaceRelease(colorSpace);
 
 
 
    //第二步 取每个点的像素值
    unsigned char* data = CGBitmapContextGetData (context);
 
    if (data == NULL){
        CGContextRelease(context);
        return 0;
    }
 
    NSCountedSet *cls=[NSCountedSet setWithCapacity:thumbSize.width*thumbSize.height];
 
  for (int x=0; x<thumbSize.height; x++) {
        for (int y=0; y<thumbSize.width; y++) {
 
            int offset = 4*(x*thumbSize.width + y);
            int red = data[offset];
            int green = data[offset+1];
            int blue = data[offset+2];
            int alpha =  data[offset+3];
 
            NSArray *clr=@[@(red),@(green),@(blue),@(alpha)];
            [cls addObject:clr];
 
        }
    }
    CGContextRelease(context);
 
    //第三步 找到出现次数最多的那个颜色
    NSEnumerator *enumerator = [cls objectEnumerator];
    NSArray *curColor = nil;
 
    NSArray *MaxColor=nil;
    float MaxCount=0;
    float allCount=0;
 //8828 10800
    while ( (curColor = [enumerator nextObject]) != nil )
    {
        NSUInteger tmpCount = [cls countForObject:curColor];
        allCount = allCount + tmpCount;
        if ( tmpCount < MaxCount ) continue;
 
        MaxCount = tmpCount;
        MaxColor=curColor;
 
    }
    //返回三原色色值
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithCapacity:0];
    [dic setValue:@([MaxColor[0] intValue]/255.0f) forKey:@"red"];
    [dic setValue:@([MaxColor[1] intValue]/255.0f) forKey:@"green"];
    [dic setValue:@([MaxColor[2] intValue]/255.0f) forKey:@"blue"];
    DDLogInfo(@"%lf", (allCount - MaxCount) / allCount);
    return (allCount - MaxCount) / allCount;
}


- (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithAuthorization:(ASAuthorization *)authorization API_AVAILABLE(ios(13.0)) {

    if ([authorization.credential isKindOfClass:[ASAuthorizationAppleIDCredential class]]) {
        ASAuthorizationAppleIDCredential * credential = (ASAuthorizationAppleIDCredential *)authorization.credential;
        // 苹果用户唯一标识符，该值在同一个开发者账号下的所有 App下是一样的，开发者可以用该唯一标识符与自己后台系统的账号体系绑定起来。
        NSString * userID = credential.user;
        
        // 苹果用户信息 如果授权过，可能无法再次获取该信息
        NSString *tokenStr = [@"ios" stringByAppendingString:userID];
        [self login:3 anduserId:userID];
       // [self rquestThirdLogin:tokenStr withEmail:email];
    } else if ([authorization.credential isKindOfClass:[ASPasswordCredential class]]) {
        // 这个获取的是iCloud记录的账号密码，需要输入框支持iOS 12 记录账号密码的新特性，如果不支持，可以忽略
        // 用户登录使用现有的密码凭证
        ASPasswordCredential * passwordCredential = (ASPasswordCredential *)authorization.credential;
        // 密码凭证对象的用户标识 用户的唯一标识
        NSString * user = passwordCredential.user;
        //把用户的唯一标识 传给后台 判断该用户是否绑定手机号，如果绑定了直接登录，如果没绑定跳绑定手机号页面
        // 密码凭证对象的密码
        NSString * password = passwordCredential.password;
        DDLogInfo(@"userID: %@", user);
        DDLogInfo(@"password: %@", password);
    } else {

    }
}

- (void)login:(int)type anduserId:(NSString *)userID{
    [[KRAlartManager shareInstance] showLodingAlertView:@"努力加载中..."];
    WEAKSELF
    NSDictionary *parameters;
    if(type == 2){
        parameters = @{@"wx_id":userID,@"type":@(type)};
    }else if(type == 3){
        parameters = @{@"apple_id":userID,@"type":@(type)};
    }else{
        NSString *phone = [[NSUserDefaults standardUserDefaults] valueForKey:USERPHONE];
        parameters = @{@"phone":phone,@"type":@(type)};
    }
    [NetworkingTool POST:User_login parameters:parameters isDeviceUrl:NO success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        [[KRAlartManager shareInstance] hidenAlartView];
        if([response[@"code"] intValue] == 0){
            if(response[@"data"] && [response[@"data"] isKindOfClass:[NSDictionary class]]){
                NSDictionary *dict = response[@"data"];
                NSString *phone = dict[@"phone"];
                if(phone.length < 1){
                    [[NSNotificationCenter defaultCenter] postNotificationName:SETPHONENUMB object:userID];
                }else{
                    [[NSUserDefaults standardUserDefaults] setObject:dict forKey:USERINFOKEY];
                    KRTabarController *vc = [[KRTabarController alloc] init];
                    [[NSUserDefaults standardUserDefaults] setObject:dict[@"phone"] forKey:USERPHONE];
                    UINavigationController *navVc = [[UINavigationController alloc] initWithRootViewController:vc];
                    [UIApplication sharedApplication].delegate.window.rootViewController = navVc;
                    
                }
            }else{
            }
        }else{
        }
        
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        
    }];
}

// 授权失败

- (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithError:(NSError *)error API_AVAILABLE(ios(13.0)) {
    NSString *errorMsg = nil;
    switch (error.code) {
        case ASAuthorizationErrorCanceled:
            errorMsg = @"用户取消了授权请求";
            break;
        case ASAuthorizationErrorFailed:
            errorMsg = @"授权请求失败";
            break;
        case ASAuthorizationErrorInvalidResponse:
            errorMsg = @"授权请求响应无效";
            break;
        case ASAuthorizationErrorNotHandled:
            errorMsg = @"未能处理授权请求";
            break;
        case ASAuthorizationErrorUnknown:
            errorMsg = @"授权请求失败未知原因";
            break;
    }
    DDLogInfo(@"%@", errorMsg);

}
- (BOOL)isopenFaceID{
    WEAKSELF
    UnlockSupportType supportType = JUnlockType_None;
    BOOL isCanEvaluatePolicy = NO;
    // 检测设备是否支持TouchID或者FaceID
    if (@available(iOS 8.0, *)) {
        weakSelf.context = [[LAContext alloc] init];
        NSError *authError = nil;
        isCanEvaluatePolicy  = [weakSelf.context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&authError];
    }
    return isCanEvaluatePolicy;
}

- (UnlockSupportType)checkUnlockSupportType{
    WEAKSELF
    UnlockSupportType supportType = JUnlockType_None;
    // 检测设备是否支持TouchID或者FaceID
    if (@available(iOS 8.0, *)) {
        weakSelf.context = [[LAContext alloc] init];
        NSError *authError = nil;
        BOOL isCanEvaluatePolicy = [weakSelf.context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&authError];
        if (authError) {
            [[KRAlartManager shareInstance] showAlert:@"请检查是否支持指纹或者脸部识别登录"];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"FACEIDLOGIN_Close" object:nil];
        } else {
            if (isCanEvaluatePolicy) {
                // 判断设备支持TouchID还是FaceID
                if (@available(iOS 11.0, *)) {
                    switch (weakSelf.context.biometryType) {
                        case LABiometryNone:
                        {
                            
                        }
                            break;
                        case LABiometryTypeTouchID:
                        {
                            supportType = JUnlockType_TouchID;
                        }
                            break;
                        case LABiometryTypeFaceID:
                        {
                            supportType = JUnlockType_FaceID;
                            
                        }
                            break;
                        default:
                            break;
                    }
                } else {
                    // Fallback on earlier versions
                    DDLogInfo(@"iOS 11之前不需要判断 biometryType");
                    // 因为iPhoneX起始系统版本都已经是iOS11.0，所以iOS11.0系统版本下不需要再去判断是否支持faceID，直接走支持TouchID逻辑即可。
                    supportType = JUnlockType_TouchID;
                }
                
            } else {
            }
        }
    } else {
        // Fallback on earlier versions
    }
    
    self.supportType = supportType;
    [self unlockWithResultBlock:^(UnlockResult result, NSString * _Nonnull errMsg) {
        if(result == JUnlockSuccess){
            if(USERINFO.token.length > 1){
                [[NSNotificationCenter defaultCenter] postNotificationName:FACEIDLOGIN object:nil];
            }else{
                [self login:4 anduserId:@""];
            }
        }else{
            [[KRAlartManager shareInstance] showAlert:@"faceID/touchID 验证失败"];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"FACEIDLOGIN_Close" object:nil];
        }
    }];
    return supportType;
}



- (void)unlockWithResultBlock:(UnlockResultBlock)block{
    WEAKSELF
    if(weakSelf.supportType == JUnlockType_None){
        //[self errorTipWithMessage:@"此设备未设置ToucID或FaceID,请使用手势登录" WithIsReturn:NO];
        return;
    }
    LAContext* jcontext = weakSelf.context;
   // jcontext.localizedFallbackTitle = @"输入密码";

    LAPolicy policyType = LAPolicyDeviceOwnerAuthenticationWithBiometrics;
    if (@available(iOS 9.0, *)) {
        policyType = LAPolicyDeviceOwnerAuthentication;
    }
    
    NSError* error = nil;
    if ([jcontext canEvaluatePolicy:policyType error:&error]) {
        
        NSString* str ;
        if(weakSelf.supportType == JUnlockType_TouchID){
            str = @"通过Home键验证已有手机指纹";
        }else if(weakSelf.supportType == JUnlockType_FaceID){
            str = @"请正对屏幕启动脸部识别";
        }
        [jcontext evaluatePolicy:policyType localizedReason:str reply:^(BOOL success, NSError * _Nullable error) {
            if (success) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    DDLogInfo(@"TouchID 验证成功");
                    //保存账号/密码/设备
                    if(block){
                        block(JUnlockSuccess,@"");
                    }
                });
            }else if(error){
                switch (error.code) {
                    case LAErrorAuthenticationFailed:{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            DDLogInfo(@"TouchID 验证失败");
                        });
                        break;
                    }
                    case LAErrorUserCancel:{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            if(block){
                                block(JUnlockFailed,@"");
                            }

                            DDLogInfo(@"TouchID 被用户手动取消");
                        });
                    }
                        break;
                    case LAErrorUserFallback:{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            DDLogInfo(@"用户不使用TouchID,选择手动输入密码");

                        });
                    }
                        break;
                    case LAErrorSystemCancel:{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            DDLogInfo(@"TouchID 被系统取消 (如遇到来电,锁屏,按了Home键等)");
                            if(block){
                                block(JUnlockFailed,@"");
                            }

                        });
                    }
                        break;
                    case LAErrorPasscodeNotSet:{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            DDLogInfo(@"TouchID 无法启动,因为用户没有设置密码");
                        });
                    }
                        break;
                    case LAErrorAppCancel:{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            DDLogInfo(@"当前软件被挂起并取消了授权 (如App进入了后台等)");
                        });
                    }
                        break;
                    case LAErrorInvalidContext:{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            DDLogInfo(@"当前软件被挂起并取消了授权 (LAContext对象无效)");
                        });
                    }
                        break;
                    default:
                        break;
                }
            }
        }];
    }else{
        block(JUnlockFailed,@"TouchID失效");
    }
}


#pragma mark - ASAuthorizationControllerPresentationContextProviding
- (ASPresentationAnchor)presentationAnchorForAuthorizationController:(ASAuthorizationController *)controller  API_AVAILABLE(ios(13.0)) {

    return UIApplication.sharedApplication.delegate.window;

}
@end
